package ynu.edu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;

import java.time.Duration;

/**
 * Resilience4j熔断器配置
 */
@Configuration
public class ResilienceConfig {

    /**
     * 配置熔断器注册表
     */
    @Bean
    public CircuitBreakerRegistry circuitBreakerRegistry() {
        // 创建默认熔断器配置
        CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
                .failureRateThreshold(50) // 超过50%的请求失败时触发熔断
                .waitDurationInOpenState(Duration.ofMillis(5000)) // 熔断后5秒内不接受请求
                .permittedNumberOfCallsInHalfOpenState(3) // 半开状态下允许3次请求尝试
                .minimumNumberOfCalls(5) // 至少需要5次调用才能计算失败率
                .slidingWindowType(CircuitBreakerConfig.SlidingWindowType.COUNT_BASED)
                .slidingWindowSize(10) // 基于最近10次请求计算失败率
                .build();
        
        return CircuitBreakerRegistry.of(circuitBreakerConfig);
    }
    
    /**
     * 配置订单服务熔断器
     */
    @Bean
    public CircuitBreaker orderServiceCircuitBreaker(CircuitBreakerRegistry registry) {
        return registry.circuitBreaker("orderServiceBreaker");
    }
} 